package name.SakanaCatcher.imgManager;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import name.SakanaCatcher.imgManager.storage.StorageFileNotFoundException;
import name.SakanaCatcher.imgManager.storage.StorageService;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


@RestController
public class FileUploadController {

	private final StorageService storageService;

	@Autowired
	public FileUploadController(StorageService storageService) {
		this.storageService = storageService;
	}

	@GetMapping("/")
	public String listUploadedFiles(Model model) throws IOException {

		model.addAttribute("files", storageService.loadAll().map(
				path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
						"serveFile", path.getFileName().toString()).build().toUri().toString())
				.collect(Collectors.toList()));

		return "uploadForm";
	}

	@GetMapping("/files/{filename:.+}")
	@ResponseBody
	public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

		Resource file = storageService.loadAsResource(filename);
		return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
				"attachment; filename=\"" + file.getFilename() + "\"").body(file);
	}
	@CrossOrigin(origins = {"http://localhost:9528", "http://localhost:9527"})
	@PostMapping("/")
	public Map<String, Object> handleFileUpload(@RequestParam("avatar") MultipartFile file) {
		String relativePath = "/img/" + file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf('.'))+ "_" +  System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'),file.getOriginalFilename().length());
		String path = ClassUtils.getDefaultClassLoader().getResource("static").getPath() + relativePath;
		File saveFile = new File(path);
		if (!saveFile.exists()){
			saveFile.mkdirs();
		}
		try {
			file.transferTo(saveFile);  //将临时存储的文件移动到真实存储路径下
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println(path);
		return Map.of( "status",200,"data","http://localhost:8090"+ relativePath);
	}

	@ExceptionHandler(StorageFileNotFoundException.class)
	public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
		return ResponseEntity.notFound().build();
	}

}
